const mongoose = require('mongoose')
const Schema = mongoose.Schema
const bcrypt = require('bcryptjs');
const { name } = require('../public/javascripts/utils');
//  用户

const schema = new Schema({
  username: { type: String, required: true, unique: true }, // 用户名
  password: { type: String, required: true ,select: false }, // 密码 (应存储为哈希值)
  firstName: { type: String, default: '' }, // 名字
  lastName: { type: String, default: '' }, // 姓氏
  profilePicture: { type: String, default: '' }, // 头像URL
  bio: { type: String, default: '' }, // 个人简介
  socialMediaLinks: { type: Object, default: {} }, // 社交媒体链接
  roles: { type: [String], default: ['user'] }, // 用户角色，默认为普通用户
  createdAt: { type: Date, default: Date.now }, // 创建时间
  updatedAt: { type: Date, default: Date.now } // 更新时间
})

schema.pre('save', async function(next) {
  if (!this.isModified('password')) {
    return next();
  }
  const salt = await bcrypt.genSalt(10);
  this.password = await bcrypt.hash(this.password, salt);
  next();
});

schema.methods.comparePassword = async function(candidatePassword) {
  return await bcrypt.compare(candidatePassword, this.password);
};
module.exports = mongoose.model(name(__filename), schema)